<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改文章</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/common.css}"/>

</head>
<body>
<form class="layui-form" action="" method="POST">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">文章标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" lay-verify="required" autocomplete="off"
                           placeholder="请输入文章标题" class="layui-input" maxlength="100" id="articleTitle">
                    <div id="titleCharCount" class="char-count  ">0/100</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">文章排序</label>
                <div class="layui-input-block">
                    <input type="number" min="0" max="65535" name="sort" placeholder="请输入文章排序"
                           class="layui-input" lay-verify="required" id="channelSort">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">头图</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" id="ID-upload-demo-btn">
                        <i class="layui-icon layui-icon-upload"></i> 头图上传
                    </button>
                    <input type="hidden" name="resourceUrl">
                    <span style="margin-left: 3px;color:red;font-size: 15px">仅支持jpg、png、webp</span>
                    <div style="width: 132px;">
                        <div class="layui-upload-list">
                            <img class="layui-upload-img" id="ID-upload-demo-img" style="width: 100%; height: 92px;">
                            <div id="ID-upload-demo-text"></div>
                        </div>
                        <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
                            <div class="layui-progress-bar" lay-percent=""></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">发布日期</label>
                <div class="layui-input-block">
                    <input name="articleTime" type="text" lay-verify="required" class="layui-input" autocomplete="off"
                           id="ID-laydate-type-datetime"
                           placeholder="yyyy-MM-dd HH:mm:ss">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <textarea name="description" placeholder="请输入文章描述" lay-verify="required"
                              class="layui-textarea"
                              autocomplete="off" maxlength="500" id="articleDescription"></textarea>
                    <div id="descCharCount" class="char-count ">0/500</div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">内容</label>
                <div class="layui-input-block">
                    <script id="uEditor" name="content" type="text/plain" style="width:100%;height:400px;">
                    </script>
                </div>
            </div>
            <div class="layui-form-item" id="struct" style="display: none">
                <label class="layui-form-label">结构</label>
                <div class="layui-input-block" id="tabContainer">
                    <div class="layui-tab">
                        <ul class="layui-tab-title" id="tabTitles">
                            <!-- 动态生成的选项卡标题将放在这里 -->
                        </ul>
                        <div class="layui-tab-content" id="tabContents">
                            <!-- 动态生成的选项卡内容将放在这里 -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">附件</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn demo-class-accept" lay-options="{accept: 'file'}">
                        <i class="layui-icon layui-icon-upload"></i>
                        上传附件
                    </button>
                    <input type="hidden" name="attachmentUrl">
                    <span id="file_p"></span>
                    <a id="removeAttachment" style="cursor: pointer;display: none">
                        <i class="layui-icon layui-icon-delete"></i>
                    </a>
                    <div style="width: 117px;margin-top: 10px">
                        <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo1">
                            <div class="layui-progress-bar" lay-percent=""></div>
                        </div>
                    </div>
                    <p style="margin-top:3px;color:red;font-size: 15px">
                        注意：仅支持上传的文件格式 (zip, rar, pdf, xlsx,doc,docx)
                    </p>
                </div>
            </div>
            <div class="layui-form-item" id="publishedDelay">
                <label class="layui-form-label">发布方式</label>
                <div class="layui-input-block">
                    <input type="radio" name="way" value="1" title="现在发布" id="now" lay-filter="way-radio-filter"
                    >
                    <input type="radio" name="way" value="2" title="定时发布" id="delay" lay-filter="way-radio-filter">
                </div>
            </div>
            <div class="layui-form-item" style="display: none" id="publishedDate">
                <label class="layui-form-label">发布日期</label>
                <div class="layui-input-block">
                    <input type="text" name="publishedTime" class="layui-input" autocomplete="off"
                           id="ID-laydate-type-datetime1"
                           placeholder="yyyy-MM-dd HH:mm:ss">
                </div>
            </div>

            <div class="layui-form-item" id="isPushed">
                <label class="layui-form-label">是否推送</label>
                <div class="layui-input-block">
                    <input type="radio" name="pw" value="1" title="否" id="pf" lay-filter="pw-radio-filter">
                    <input type="radio" name="pw" value="2" title="是" id="pt" lay-filter="pw-radio-filter">
                </div>
            </div>
            <div class="layui-form-item" style="display: none" id="selectChannel">
                <label class="layui-form-label">选择栏目</label>
                <div class="layui-input-block">
                    <input type="text" id="parent-tree-input" placeholder="请选择栏目" class="layui-input"
                           readonly="readonly">
                    <!-- 清空按钮 -->
                    <button type="button" id="clear-parent" class="layui-btn  layui-btn-sm"
                            style="position: absolute; right: 5px; top: 5px;">
                        清空
                    </button>
                    <!-- 用于提交的隐藏字段 -->
                    <div id="parent-tree"
                         style="display:none; position: absolute; z-index: 1000; background-color: #fff; border: 1px solid #d2d2d2; width: 50%"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn   layui-btn-sm" lay-submit="" lay-filter="article-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>

<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:src="@{/pear/component/ueditor/ueditor.config.js}"></script>
<script th:src="@{/pear/component/ueditor/ueditor.all.js}"></script>
<script th:src="@{/pear/component/ueditor/lang/zh-cn/zh-cn.js}"></script>
<script th:inline="javascript">
    let baseURL = /*[[@{/}]]*/ '';
    layui.use(['form', 'jquery', 'upload', 'element', 'laydate', 'tree'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let element = layui.element;
        let upload = layui.upload;
        let tree = layui.tree;
        let laydate = layui.laydate;
        let structParamList = []; // 用于存储结构参数列表
        let formData = []; // 用于存储收集到的数据

// 获取频道信息
        $.ajax({
            url: baseURL + "cms/channel/select",
            type: 'GET',
            data: {
                channelId: parent.channelId
            },
            success: function (res) {
                console.log(res.data);
                if (res.code === 1000) {
                    if ((res.data.type === 10 || res.data.type === 13) && res.data.structId != null) {
                        $('#struct').show(); // 显示结构部分

                        // 获取结构参数
                        $.ajax({
                            url: baseURL + "cms/struct/getStructParamByStructId?structId=" + res.data.structId,
                            type: 'GET',
                            success: function (data) {
                                structParamList = data.data; // 存储结构参数列表
                                console.log(structParamList);
                                buildTabs(structParamList);
                            }
                        });

                        // 获取文章参数
                        $.ajax({
                            url: baseURL + "cms/articleParam/list?articleId=" + parent.articleId,
                            type: 'GET',
                            success: function (result) {
                                if (result.data && result.data.length > 0) {
                                    structParamList = result.data; // 使用文章参数列表
                                    console.log(structParamList);
                                    buildTabs(structParamList);
                                }
                            }
                        });
                    } else {
                        $('#struct').hide(); // 隐藏结构部分
                    }
                }
            }
        });

// 构建选项卡的函数
        function buildTabs(structParamList) {
            if (!structParamList || structParamList.length === 0) {
                console.error("没有获取到有效的结构参数列表");
                return;
            }

            // 获取选项卡标题和内容容器
            const tabTitlesContainer = document.getElementById("tabTitles");
            const tabContentsContainer = document.getElementById("tabContents");

            // 清空之前的选项卡标题和内容
            tabTitlesContainer.innerHTML = '';
            tabContentsContainer.innerHTML = '';

            structParamList.forEach(function (structParam, index) {
                // 创建选项卡标题
                const tabTitleElement = document.createElement("li");
                tabTitleElement.className = index === 0 ? "layui-this" : ""; // 默认选中第一个
                tabTitleElement.id = `tabTitle-${index}`;
                tabTitleElement.textContent = structParam.nameEn || structParam.name; // 兼容不同字段
                tabTitlesContainer.appendChild(tabTitleElement);

                // 创建选项卡内容
                const tabContentElement = document.createElement("div");
                tabContentElement.className = "layui-tab-item" + (index === 0 ? " layui-show" : ""); // 默认显示第一个
                tabContentElement.id = `tabContent-${index}`;

                // 创建输入框
                const inputElement = document.createElement("textarea");
                inputElement.className = "layui-textarea";
                inputElement.placeholder = `请输入 ${structParam.name || structParam.nameEn} 的内容`;
                inputElement.name = `input-${index}`; // 为每个输入框设置唯一的 name 属性

                // 如果有默认值，回显内容
                if (structParam.value) {
                    inputElement.value = structParam.value;
                }

                // 将输入框添加到内容区域
                tabContentElement.appendChild(inputElement);

                // 将内容区域添加到容器
                tabContentsContainer.appendChild(tabContentElement);
            });

            // 为选项卡标题绑定点击事件
            document.querySelectorAll("#tabTitles li").forEach((titleElement, index) => {
                titleElement.addEventListener("click", function () {
                    // 移除所有标题的选中状态
                    document.querySelectorAll("#tabTitles li").forEach(li => {
                        li.classList.remove("layui-this");
                    });
                    // 添加当前标题的选中状态
                    titleElement.classList.add("layui-this");

                    // 隐藏所有内容区域
                    document.querySelectorAll(".layui-tab-item").forEach(content => {
                        content.classList.remove("layui-show");
                    });

                    // 显示当前点击的选项卡内容
                    document.getElementById(`tabContent-${index}`).classList.add("layui-show");
                });
            });
        }

// 收集数据的函数
        function collectData() {
            formData = []; // 清空之前的收集数据
            if (structParamList && structParamList.length > 0) {
                structParamList.forEach((structParam, index) => {
                    const inputElement = document.querySelector(`textarea[name='input-${index}']`);
                    const userValue = inputElement.value;

                    formData.push({
                        name: structParam.nameEn || structParam.name, // 兼容不同字段
                        description: structParam.description || structParam.name, // 兼容不同字段
                        value: userValue // 用户输入的值
                    });
                });
            }
            return formData; // 返回收集到的数据
        }

        // 使用 jQuery 来监听标题输入框的输入事件
        $('#articleTitle').on('input', function () {
            let maxLength = $(this).attr('maxlength');
            let currentLength = $(this).val().length;
            $('#titleCharCount').text(currentLength + "/" + maxLength);
        });

        // 使用 jQuery 来监听描述输入框的输入事件
        $('#articleDescription').on('input', function () {
            let maxLength = $(this).attr('maxlength');
            let currentLength = $(this).val().length;
            $('#descCharCount').text(currentLength + "/" + maxLength);
        });

        laydate.render({
            elem: '#ID-laydate-type-datetime',
            type: 'datetime',
            fullPanel: true,
        });
        laydate.render({
            elem: '#ID-laydate-type-datetime1',
            type: 'datetime',
            fullPanel: true,
        });
        form.on('radio(way-radio-filter)', function (data) {
            if (Number(data.elem.value) === 2) {
                $('#publishedDate').show();
            } else {
                $('#publishedDate').hide();
                $('input[name=publishedTime]').val();
            }
        });


        if (parent.publishedTime !== "" && parent.publishedTime !== null) {
            $('#delay').prop('checked', true)
            $('#publishedDate').show();
            $('input[name=publishedTime]').val(parent.publishedTime);
            form.render('radio');
        } else {
            $('#now').prop('checked', true)
            form.render('radio');
        }


        $('#contentEditor').on('input', function () {
            editor.setHtml(this.value);
        });

        let channelTitles = parent.channelNames
        let channelIds = parent.channelIds
        form.on('radio(pw-radio-filter)', function (data) {
            if (Number(data.elem.value) === 2) {
                $('#selectChannel').show();
                channelTitles = parent.channelNames
                channelIds = parent.channelIds
                $('#parent-tree-input').val(channelTitles);
            } else {
                $('#selectChannel').hide();
                channelTitles = ""
                channelIds = []
            }
        });


        // 初始化树形结构的隐藏状态
        $('#parent-tree').hide();

        // 点击输入框时显示树形结构
        $('#parent-tree-input').on('click', function () {
            $('#parent-tree').toggle(); // 显示或隐藏树形结构
        });

        // 渲染父级栏目树形结构


        if (channelIds.length > 0) {
            $('#parent-tree-input').val(channelTitles); // 填充栏目名称
            $('#pt').prop('checked', true)
            form.render('radio')
            $('#selectChannel').show();
        } else {
            $('#pf').prop('checked', true)
            form.render('radio')
            $('#selectChannel').hide();
        }
        $.get(baseURL + "cms/channel/getParentMenus", function (data) {
            let d;
            if (data != null) {
                d = filterByChannelId(data, parent.channelId)
                d = findNodesWithCodeList(d)
            }
            tree.render({
                elem: '#parent-tree', // 树形组件容器
                data: d, // 后端返回的树形数据
                click: function (obj) {
                    if (obj && obj.data) {
                        if (channelTitles.includes(obj.data.title)) {
                            return;
                        }
                        let s = "";
                        if (channelTitles === "") {
                            s = "";
                        } else {
                            s = ",";
                        }
                        channelTitles += s + obj.data.title
                        channelIds.push(obj.data.id)
                        $('#parent-tree-input').val(channelTitles); // 填充栏目名称
                        // $('#parent-tree').hide(); // 隐藏树形选择框
                    } else {
                        console.error("无法获取节点数据");
                    }
                }
            });
        });

        // 点击清空按钮时，清空输入框和隐藏树形结构
        $('#clear-parent').on('click', function () {
            $('#parent-tree-input').val(''); // 清空输入框
            channelIds = []
            channelTitles = ""
            $('#parent-tree').hide(); // 隐藏树形结构
        });
        // 点击空白区域时，关闭树形选择框
        $(document).on('click', function (e) {
            if (!$(e.target).closest('#parent-tree-input').length && !$(e.target).closest('#parent-tree').length) {
                $('#parent-tree').hide();
            }
        });

        // 树组件过滤函数
        function filterByChannelId(data, channelId) {
            return data.filter(item => {
                if (item.id == channelId) {
                    return false;
                }
                if (item.children && item.children.length > 0) {
                    item.children = filterByChannelId(item.children, channelId);
                    return true;
                }
                return true;
            });
        }


        function findNodesWithCodeList(data) {
            let result = []; // 用于存储符合条件的节点

            function recursiveSearch(nodes) {
                if (!nodes || nodes.length === 0) return;

                for (let node of nodes) {
                    if (node.code === "LIST") {
                        result.push(node); // 如果当前节点的 code 是 "LIST"，加入结果数组
                    }
                    if (node.children && node.children.length > 0) {
                        recursiveSearch(node.children); // 递归查找子节点
                    }
                }
            }

            recursiveSearch(data); // 从根节点开始递归查找
            return result; // 返回结果数组
        }


        // 往UEditor编辑头部工具栏中添加一个自定义名为 newbtn 的功能按扭


        let ue = UE.getEditor('uEditor', {
            serverUrl: baseURL + 'cms/ueditor/upload',
            autoFloatEnabled: false,
        });

        // 设置内容（回显）
        UE.getEditor('uEditor').ready(function () {
            this.setContent(parent.content);
        });


        // 单图片上传
        let uploadImg = upload.render({
            elem: '#ID-upload-demo-btn',
            url: baseURL + 'cms/infoArticle/uploadImg',
            size: parent.resourceSize,
            acceptMime: 'image/jpeg, image/png, image/webp',
            before: function (obj) {
                element.progress('filter-demo', '0%');
                layer.msg('上传中', {icon: 16, time: 0});
            },
            done: function (res) {
                if (res.code === 1000) {
                    $('#ID-upload-demo-img').attr('src', baseURL + res.data);
                    $("[name=resourceUrl]").val(res.data);
                    $('#ID-upload-demo-text').html('');
                    return
                }
                return layer.msg(res.msg, {icon: 2, time: 2000});
            },
            // 进度条
            progress: function (n) {
                element.progress('filter-demo', n + '%');
                if (n === 100) {
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });

        //附件上传
        let uploadAttachment = upload.render({
            elem: '.demo-class-accept',
            url: baseURL + 'cms/infoArticle/uploadAttachment',
            accept: 'file',
            exts: 'zip|rar|pdf|xlsx|doc|docx',
            size: parent.attachmentSize,
            before: function (obj) {
                element.progress('filter-demo1', '0%');
                layer.msg('上传中', {icon: 16, time: 0});
            },
            done: function (res) {
                if (res.code === 1000) {
                    $("[name=attachmentUrl]").val(res.data);
                    const fileName = res.data.split('/').pop().split('_').slice(1).join('_');
                    $('#file_p').html(`${fileName}
                        <a href="${baseURL}${res.data}" download="${fileName}" style="margin-left: 10px; color: #1e9fff;">
                        点击下载查看附件
                        </a>
                    `);
                    $('#removeAttachment').show()
                    layer.msg('上传完毕', {icon: 1, time: 2000});
                    return;
                }
                $('#file_p').html('上传失败，请重试！').css('color', 'red');
                element.progress('filter-demo1', '0%');
                layer.msg(res.msg, {icon: 2, time: 2000});
            }, progress: function (n) {
                element.progress('filter-demo1', n + '%');
            }
        })

        $('#removeAttachment').on('click', function () {
            layer.confirm('确定要删除附件吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                element.progress('filter-demo', '0%');
                $("[name=attachmentUrl]").val('');
                $('#file_p').html('');
                $('#removeAttachment').hide()
            })
        });

        // 表单提交
        form.on('submit(article-save)', function (data) {
            let way = data.field.way
            let publishedTime = data.field.publishedTime
            if (Number(way) === 2) {
                if (!publishedTime) {
                    layer.msg("请填写发布日期！", {icon: 2, time: 1500});
                    return false;
                } else {
                    const time = new Date(publishedTime);
                    const currentTime = new Date();
                    currentTime.setMinutes(currentTime.getMinutes() + 1);
                    if (time <= currentTime) {
                        layer.msg("定时发布时间必须大于当前时间一分钟！", {icon: 2, time: 1500});
                        return false;
                    }
                }
            } else {
                data.field.publishedTime = null
            }
            data.field.channelId = parent.channelId
            data.field.articleId = parent.articleId
            data.field.contentId = parent.contentId
            data.field.status = parent.state
            channelIds.push(parent.channelId)
            data.field.channelIds = channelIds
            data.field.infoParam = collectData()
            let loading = layer.msg('正在提交中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            });
            console.log(data.field)
            $.ajax({
                url: baseURL + 'cms/infoArticle/update',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            parent.layui.table.reload("article-table");
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
            return false;
        });
    });
</script>
</body>
</html>

